<template>
  <div>
<!--    <el-upload-->
<!--      list-type="picture-card"-->
<!--      :action="`${path}/upload/upload`"-->
<!--      :headers="{ 'x-token': token }"-->
<!--      :show-file-list="showFileList"-->
<!--      :on-success="handleImageSuccess"-->
<!--      :before-upload="beforeImageUpload"-->
<!--      :on-preview="handlePictureCardPreview"-->
<!--      :on-remove="handleRemove"-->
<!--    >-->
<!--      <i class="el-icon-plus"></i>-->
<!--    </el-upload>-->

    <el-upload
        track-by="image"
        :action="`${path}/admin/upload/upload`"
        :headers="{ 'x-token': token }"
        list-type="picture-card"
        :file-list="fileList"
        :before-upload="beforeImageUpload"
        :on-success="handleImageSuccess"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
const path = process.env.VUE_APP_BASE_API;
import { mapGetters } from "vuex";
export default {
  name: "upload-image",
  model: {
    prop: "imageUrl",
    event: "change",
  },
  props: {
    fileList:{
      type: Array,
      default: ()=>([]),
    },
    imageUrl: {
      type: String,
      default: "",
    },
    compressSize: {
      type: Number,
      default: 256, // 256KB 超出后执行压缩
    },
    maxSize: {
      type: Number,
      default: 512 , // 512KB 超出后执行报错
    },
    maxWH: {
      type: Number,
      default: 1920, // 图片长宽上限
    },
  },
  data() {
    return {
      dialogImageUrl:'',
      path: path,
      dialogVisible: false
    };
  },
  computed: {
    ...mapGetters("user", ["userInfo", "token"]),
  },
  methods: {
    beforeImageUpload(file) {
      const isRightSize = file.size  / 1024< this.maxSize;
      if (!isRightSize) {
        this.$message.error('文件大小不能超过 '+this.maxSize+'KB!');
        return false
      }
      return true
      // let isRCompress = file.size / 1024 < this.compressSize;
      // if (!isRCompress) {
      //   // 压缩
      //   let compress = new ImageCompress(file, this.compressSize, this.maxWH);
      //   return compress.compress();
      // }
      // return isRCompress;
    },
    handleImageSuccess(res) {
      const { data } = res;
      if (data.file) {
        const urls = this.fileList.map(item=>item)
        console.log(data.file)
        urls.push(data.file.url)

        this.$emit("change", urls);
      }
    },
    handleRemove(file, fileList) {
      const urls = this.fileList.map(item=>item.url)
      var index = urls.indexOf(file);
      if (index > -1) {
        urls.splice(index, 1);
      }
      this.$emit("change", urls);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }
  },
};
</script>
